<template>
  <div class="assignment-area">
    <!-- 作业栏标题 -->
    <h2 class="title">作业栏</h2>

    <!-- 作业表格 -->
    <div class="assignment-table">
      <el-table :data="tableData" stripe>
        <el-table-column label="作业Id" prop="id" />
        <el-table-column label="作业名称" prop="name" />
        <el-table-column label="截止日期" prop="deadline" />
        <el-table-column label="文件">
          <template #default="scope">
            <span>{{ scope.row.file }}</span>
            <button class="download-btn" @click="handleDownload(scope.row.id)">下载</button>
          </template>
        </el-table-column>

        <!-- 新增上传作业栏 -->
        <el-table-column label="上传作业">
          <template #default="scope">
            <!-- 隐藏的文件选择框，点击按钮时触发 -->
            <input 
              type="file" 
              :id="`fileInput_${scope.row.id}`" 
              @change="handleFileChange($event, scope.row.id)" 
              style="display: none" 
            />
            <button class="select-file-btn" @click="handleSelectFile(scope.row.id)">选择文件</button>
            <button class="upload-btn" @click="handleUpload(scope.row.id)">上传作业</button>
          </template>
        </el-table-column>

        <!-- 显示互评状态 -->
        <el-table-column label="互评状态">
          <template #default="scope">
            <el-tag v-if="scope.row.isMutual === 'true'" type="success">已设置互评</el-tag>
            <el-button 
              v-if="scope.row.isMutual === 'true'" 
              type="primary" 
              @click="navigateToEvaluation(scope.row.id)"
            >进入互评</el-button>
            <el-tag v-else type="info">未设置互评</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

axios.defaults.baseURL = 'http://localhost:8085';

const tableData = ref([]); // 初始化为空数组
const selectedFiles = ref({});
const router = useRouter();

// 获取作业数据的函数
const fetchHomeworkData = async (courseId) => {
  try {
    const response = await axios.get('/homework/viewhomeworkitem', {
      params: { courseId },
    });
    if (response.data) {
      tableData.value = response.data.map(item => ({
        id: item.homeworkId,
        name: item.title,
        deadline: item.deadLine,
        file: item.fileName,
        isMutual: item.isMutual || 'false',
      }));
    } else {
      console.error('返回数据为空:', response);
    }
  } catch (error) {
    console.error('获取作业数据失败:', error);
  }
};

// 调用获取作业数据的函数
onMounted(() => {
  const courseId = 1; // 替换为实际的 courseId
  fetchHomeworkData(courseId);
});

// 下载按钮点击事件
const handleDownload = async (homeworkId) => {
  try {
    const response = await axios.get('/homework/downloadhomeworkitem', {
      params: { homeworkId },
      responseType: 'blob',
    });

    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `homework_${homeworkId}.pdf`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    console.error('下载作业失败:', error);
  }
};

// 选择文件
const handleSelectFile = (homeworkId) => {
  const input = document.querySelector(`#fileInput_${homeworkId}`);
  if (input) {
    input.click();
  }
};

// 处理文件选择
const handleFileChange = (event, homeworkId) => {
  selectedFiles.value[homeworkId] = event.target.files[0];
};

// 上传作业
const handleUpload = async (homeworkId) => {
  const file = selectedFiles.value[homeworkId];
  if (!file) {
    alert('请先选择文件！');
    return;
  }

  const formData = new FormData();
  formData.append('file', file);
  formData.append('homeworkId', homeworkId);
  formData.append('userId', 1);

  try {
    const response = await axios.post('/homework/submithomework', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    console.log('上传成功:', response.data);
  } catch (error) {
    console.error('上传作业失败:', error);
  }
};

// 跳转到互评页面
const navigateToEvaluation = (homeworkId) => {
  router.push({
    name: 'MutualEvaluation',
    params: { homeworkId },
  });
};
</script>


<style scoped>
.assignment-area {
  width: 80%;
  margin: 0 auto;
  text-align: center;
}

.title {
  font-size: 50px;
  font-weight: bold;
  margin-bottom: 20px;
}

.assignment-table {
  width: 100%;
  border-collapse: collapse;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.download-btn {
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
  margin-left: 5px;
}

.download-btn:hover {
  background-color: darkred;
}

.select-file-btn {
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
  margin-right: 5px;
}

.select-file-btn:hover {
  background-color: #0b7dda;
}

.upload-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  margin-top: 5px;
}

.upload-btn:hover {
  background-color: #45a049;
}
</style>
